package com.wooming.myserver.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wooming.myserver.auth.JwtAuthenticationToken;
import com.wooming.myserver.dto.JwtDTO;
import com.wooming.myserver.security.JWT;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT 认证过滤器
 *
 * @author wooming 2025/05/22
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 获取请求头中的 JWT
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String jwt = authorizationHeader.substring(7);
            // 解析和验证 JWT 的逻辑
            try {
                if (JWT.verifyJWT(jwt)) {
                    // 解析 JWT
                    JwtDTO jwtDTO = JWT.decode(jwt);
                    String json = new ObjectMapper().writeValueAsString(jwtDTO);

                    // 创建 Authentication 对象并设置到 SecurityContextHolder 中
                    JwtAuthenticationToken authentication = new JwtAuthenticationToken(json);
                    authentication.setAuthenticated(true);

                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        filterChain.doFilter(request, response);
    }
}
